<template>
  <div class="detail-container">
    <div>
      <el-steps :active="stepStatusFormat(salesOrder.status)" finish-status="success" align-center>
        <el-step title="创建订单" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="已提交" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="提案确认中" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="提案已确认" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="合同已签订" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="生成发货计划" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="已发货" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
        <el-step title="已完成" :description="parseTime(salesOrder.createTime, '{y}-{m}-{d}')" />
      </el-steps>
      <el-card shadow="never" style="margin-top: 15px">
        <!-- 操作栏 -->
        <div class="operate-container">
          <i class="el-icon-warning color-danger" style="margin-left: 20px" />
          <span class="color-danger">当前订单状态：{{ orderStatusFormat(salesOrder.orderStatus) }}</span>
          <div class="operate-button-container">
            <el-button v-if="salesOrder.orderStatus == null || salesOrder.orderStatus =='created'" size="mini" @click="handleSave">保存订单</el-button>
            <el-button v-if="salesOrder.orderStatus == null || salesOrder.orderStatus =='created'" size="mini" @click="handleSubmit">提交订单</el-button>
            <el-button size="mini" @click="handleDownloadQuote">下载提案/报价</el-button>
            <el-button size="mini" @click="handleConfirmQuote">确认提案</el-button>
            <el-button size="mini" @click="openSignContractDialog">签订合同</el-button>
            <el-button size="mini" @click="openConfirmPayDialog">确认支付</el-button>
            <el-button size="mini" @click="openDeliveryPlanDialog">发货计划</el-button>
            <el-button size="mini" @click="openDeliveryDialog">确认发货</el-button>
          </div>
        </div>
        <!-- 基本信息 -->
        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266" />
          <span class="font-small">基本信息</span>
        </div>
        <div class="table-layout">
          <el-row>
            <el-col :span="6" class="table-cell-title">订单单号</el-col>
            <el-col :span="6" class="table-cell-title">订单类型</el-col>
            <el-col :span="6" class="table-cell-title">订单来源</el-col>
            <el-col :span="6" class="table-cell-title">销售人员</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell">
              {{ salesOrder.salesOrderNo || '--' }}
            </el-col>
            <el-col :span="6" class="table-cell">
              {{ orderTypeFormat(salesOrder.orderType) }}
            </el-col>
            <el-col :span="6" class="table-cell">
              <el-select v-model="salesOrder.sourceType" style="width: 100%" placeholder="请选择订单来源">
                <el-option v-for="option in options.sourceTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
              </el-select>
            </el-col>
            <el-col :span="6" class="table-cell">
              <el-select v-model="salesOrder.salesManId" style="width: 100%" placeholder="请选择销售人员" @change="handleSelectedSalesMan">
                <el-option v-for="option in options.salesManOptions" :key="option.id" :label="option.nickName" :value="option.id" />
              </el-select>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell-title">提案/报价</el-col>
            <el-col :span="6" class="table-cell-title">提案/报价时间</el-col>
            <el-col :span="6" class="table-cell-title">合同编号</el-col>
            <el-col :span="6" class="table-cell-title">合同签订时间</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell">{{ salesOrder.quoteUrl }}</el-col>
            <el-col :span="6" class="table-cell">{{ salesOrder.confirmQuoteTime }}</el-col>
            <el-col :span="6" class="table-cell">{{ salesOrder.contractNo }}</el-col>
            <el-col :span="6" class="table-cell">{{ salesOrder.signContractTime }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell-title">支付方式</el-col>
            <el-col :span="6" class="table-cell-title">支付时间</el-col>
            <el-col :span="6" class="table-cell-title">发货信息</el-col>
            <el-col :span="6" class="table-cell-title">发货时间</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell">{{ payTypeFormat(salesOrder.payType) }}</el-col>
            <el-col :span="6" class="table-cell">{{ salesOrder.payTime }}</el-col>
            <el-col :span="6" class="table-cell">{{ expressInfoFormat(salesOrder) }}</el-col>
            <el-col :span="6" class="table-cell">{{ salesOrder.deliveryTime }}</el-col>
          </el-row>
        </div>
        <!-- 客户信息 -->
        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266" />
          <span class="font-small">客户信息</span>
        </div>
        <div class="table-layout">
          <el-row>
            <el-col :span="6" class="table-cell-title">客户名称</el-col>
            <el-col :span="6" class="table-cell-title">客户类型</el-col>
            <el-col :span="6" class="table-cell-title">客户联系人</el-col>
            <el-col :span="6" class="table-cell-title">联系人电话</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell">
              <el-select v-model="salesOrder.customerId" style="width: 100%" placeholder="请选择客户" @change="handleSelectedCustomer">
                <el-option v-for="option in options.customerOptions" :key="option.id" :label="option.customerName" :value="option.id" />
              </el-select>
            </el-col>
            <el-col :span="6" class="table-cell">
              {{ salesOrder.customerTypeName }}
            </el-col>
            <el-col :span="6" class="table-cell">
              {{ salesOrder.customerContactName }}
            </el-col>
            <el-col :span="6" class="table-cell">
              {{ salesOrder.customerContactPhone }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell-title">收货人</el-col>
            <el-col :span="6" class="table-cell-title">收货人电话</el-col>
            <el-col :span="6" class="table-cell-title">省市区</el-col>
            <el-col :span="6" class="table-cell-title">详细地址</el-col>
          </el-row>
          <el-row>
            <el-col :span="6" class="table-cell">
              <el-input v-model="salesOrder.receiver" placeholder="请输入收货人" />
            </el-col>
            <el-col :span="6" class="table-cell">
              <el-input v-model="salesOrder.receiverPhone" placeholder="请输入收货人电话" />
            </el-col>
            <el-col :span="6" class="table-cell">
              <el-cascader v-model="selectedRegion" :options="options.regionOptions" :props="{value: 'id', label: 'regionName'}" style="width: 100%" placeholder="请选择省市区" clearable />
            </el-col>
            <el-col :span="6" class="table-cell">
              <el-input v-model="salesOrder.receiverAddress" placeholder="请输入详细地址" />
            </el-col>
          </el-row>
        </div>
        <!-- 商品信息 -->
        <div style="float: right; padding-top: 25px;">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddGoods">添加商品</el-button>
        </div>
        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266" />
          <span class="font-small">商品信息</span>
        </div>
        <el-table ref="itemTable" :data="salesOrder.items" style="width: 100%;margin-top: 20px" border>
          <el-table-column label="商品" align="center">
            <template slot-scope="scope">
              <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['spuSelector'].reset()">
                <spu-selector ref="spuSelector" @selected="handleSelectedGoods($event, scope.row)" />
                <el-input slot="reference" v-model="scope.row.spuName" placeholder="点击选择商品" readonly />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="品牌" align="center">
            <template slot-scope="scope">
              {{ scope.row.brandName }}
            </template>
          </el-table-column>
          <el-table-column label="分类" align="center">
            <template slot-scope="scope">
              {{ scope.row.categoryName }}
            </template>
          </el-table-column>
          <el-table-column label="货号" align="center">
            <template slot-scope="scope">
              {{ scope.row.sn }}
            </template>
          </el-table-column>
          <el-table-column label="价格" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" placeholder="请输入价格" @change.native="handleTotal" />
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.qty" placeholder="请输入数量" @change.native="handleTotal" />
            </template>
          </el-table-column>
          <el-table-column label="小计" align="center">
            <template slot-scope="scope">
              ￥{{ scope.row.price * scope.row.qty }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleRemoveGoods(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="float: right;margin: 20px">
          合计：<span class="color-danger">￥{{ salesOrder.totalMoney }}</span>
        </div>
        <!-- 操作信息 -->
        <div style="margin-top: 20px">
          <svg-icon icon-class="marker" style="color: #606266" />
          <span class="font-small">操作信息</span>
        </div>
        <el-table ref="orderEventTable" :data="salesOrder.events" style="margin-top: 20px;width: 100%" border>
          <el-table-column label="操作者" align="center">
            <template slot-scope="scope">
              {{ scope.row.operateMan }}
            </template>
          </el-table-column>
          <el-table-column label="操作时间" align="center">
            <template slot-scope="scope">
              {{ formatTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="原订单状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.preStatus }}
            </template>
          </el-table-column>
          <el-table-column label="订单状态" align="center">
            <template slot-scope="scope">
              {{ scope.row.orderStatus }}
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center">
            <template slot-scope="scope">
              {{ scope.row.note }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 签订合同 Dialog -->
      <el-dialog title="签订合同" :visible.sync="signContractDialogVisible" width="500px">
        <el-form :model="salesOrder" label-width="80px">
          <el-form-item label="合同编号" prop="contactId">
            <el-input v-model="salesOrder.contractNo" placeholder="请输入合同编号" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="signContractDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSignContract">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 确认支付 Dialog -->
      <el-dialog title="确认支付" :visible.sync="confirmPayDialogVisible" width="500px">
        <el-form :model="salesOrder" label-width="100px">
          <el-form-item label="支付类型" prop="contactId">
            <el-select v-model="salesOrder.payType" style="width: 100%" placeholder="请选择支付类型">
              <el-option v-for="option in options.payTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="交易流水号" prop="contactId">
            <el-input v-model="salesOrder.transactionId" placeholder="请输入交易流水号" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="confirmPayDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleConfirmPay">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 发货计划 Dialog -->
      <el-dialog title="发货计划" :visible.sync="deliveryPlanDialogVisible" width="500px">
        <el-table ref="itemTable" :data="salesOrder.items" style="width: 100%;margin-top: 20px" border>
          <el-table-column label="订单明细" align="center">
            <template slot-scope="scope">
              {{ scope.row.itemNo }}
            </template>
          </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deliveryPlanDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDeliveryPlan">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 确认发货 Dialog -->
      <el-dialog title="确认发货" :visible.sync="deliveryDialogVisible" width="500px">
        <el-form :model="salesOrder" label-width="100px">
          <el-form-item label="物流公司" prop="contactId">
            <el-select v-model="salesOrder.expressCompanyName" style="width: 100%" placeholder="请选择物流公司">
              <el-option v-for="option in options.expressCompanyOptions" :key="option.id" :label="option.expressCompanyName" :value="option.expressCompanyName" />
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号" prop="contactId">
            <el-input v-model="salesOrder.expressNo" placeholder="请输入物流单号" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="deliveryDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleDelivery">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import SalesOrderApi from '@/api/order/SalesOrderApi'
import DictValueApi from '@/api/system/DictValueApi'
import UserApi from '@/api/system/UserApi'
import RegionApi from '@/api/system/RegionApi'
import SpuApi from '@/api/goods/SpuApi'
import CustomerApi from '@/api/basic/CustomerApi'
import ExpressCompanyApi from '@/api/order/ExpressCompanyApi'
import SpuSelector from '@/views/goods/spu/SpuSelector'

const defaultSalesOrder = {
  orderType: 'internal_sales',
  sourceType: null,
  payType: null,
  payTime: null,
  salesManId: null,
  salesMan: null,
  customerId: null,
  customerName: null,
  customerTypeName: null,
  customerContactName: null,
  customerContactPhone: null,
  receiver: null,
  receiverPhone: null,
  receiverProvince: null,
  receiverCity: null,
  receiverDistrict: null,
  receiverAddress: null,
  totalQty: 0,
  totalMoney: 0,
  quoteUrl: null,
  confirmQuoteTime: null,
  contractNo: null,
  signContractTime: null,
  expressNo: null,
  expressCompanyName: null,
  deliveryTime: null,
  orderStatus: null,
  items: []
}
export default {
  name: 'SalesOrderForm',
  components: {
    SpuSelector
  },
  data() {
    return {
      options: {
        orderTypeOptions: [],
        sourceTypeOptions: [],
        salesOrderStatusOptions: [],
        salesManOptions: [],
        payTypeOptions: [],
        goodsOptions: [],
        customerOptions: [],
        regionOptions: [],
        expressCompanyOptions: []
      },
      salesOrder: Object.assign({}, defaultSalesOrder),
      selectedRegion: [], // 选中省市区的值
      signContractDialogVisible: false,
      confirmPayDialogVisible: false,
      deliveryPlanDialogVisible: false,
      deliveryDialogVisible: false
    }
  },
  watch: {
    selectedRegion(val, oldVal) {
      if (val != null) {
        this.salesOrder.receiverProvince = val[0]
        this.salesOrder.receiverCity = val[1]
        this.salesOrder.receiverDistrict = val[2]
      } else {
        this.salesOrder.receiverProvince = null
        this.salesOrder.receiverCity = null
        this.salesOrder.receiverDistrict = null
      }
    }
  },
  created() {
    this.loadOptions()
    if (this.$route.params.id) {
      this.init()
    }
  },
  methods: {
    init() {
      SalesOrderApi.get(this.$route.params.id).then(response => {
        this.salesOrder = response.data
        // 显示省市区
        this.selectedRegion = [response.data.receiverProvince, response.data.receiverCity, response.data.receiverDistrict]
      })
    },
    loadOptions() {
      DictValueApi.list({ dictCode: 'oms_sales_order_type' }).then(response => {
        this.options.orderTypeOptions = response.data
      })
      DictValueApi.list({ dictCode: 'oms_sales_order_source' }).then(response => {
        this.options.sourceTypeOptions = response.data
      })
      DictValueApi.list({ dictCode: 'oms_sales_order_status' }).then(response => {
        this.options.salesOrderStatusOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_payment_type' }).then(response => {
        this.options.payTypeOptions = response.data
      })
      SpuApi.list().then(response => {
        this.options.goodsOptions = response.data
      })
      UserApi.roleUsers({ roleId: '1356074716665876480' }).then(response => {
        this.options.salesManOptions = response.data
      })
      CustomerApi.list().then(response => {
        this.options.customerOptions = response.data
      })
      RegionApi.tree().then(response => {
        this.options.regionOptions = this.$common.list2Tree(response.data)
      })
      ExpressCompanyApi.list().then(response => {
        this.options.expressCompanyOptions = response.data
      })
    },
    openSignContractDialog() {
      this.signContractDialogVisible = true
    },
    openConfirmPayDialog() {
      this.confirmPayDialogVisible = true
    },
    openDeliveryPlanDialog() {
      this.deliveryPlanDialogVisible = true
    },
    openDeliveryDialog() {
      this.deliveryDialogVisible = true
    },
    handleSelectedCustomer(customerId) {
      CustomerApi.get(customerId).then(response => {
        this.salesOrder.customerId = response.data.id
        this.salesOrder.customerName = response.data.customerName
        this.salesOrder.customerTypeName = response.data.customerTypeName
        this.salesOrder.customerContactName = response.data.contactName
        this.salesOrder.customerContactPhone = response.data.contactPhone
        this.salesOrder.receiver = response.data.contactName
        this.salesOrder.receiverPhone = response.data.contactPhone
        this.salesOrder.receiverAddress = response.data.address
        // 显示省市区
        this.selectedRegion = [response.data.province, response.data.city, response.data.district]
      })
    },
    handleSelectedSalesMan(salesManId) {
      UserApi.get(salesManId).then(response => {
        this.salesOrder.salesManId = response.data.id
        this.salesOrder.salesMan = response.data.nickName
      })
    },
    handleAddGoods() {
      this.salesOrder.items.push({
        spuId: null,
        spuName: null,
        brandId: null,
        brandName: null,
        categoryId: null,
        categoryName: null,
        sn: null,
        price: null,
        qty: null,
        image: null
      })
    },
    handleRemoveGoods(row) {
      this.salesOrder.items.splice(this.salesOrder.items.indexOf(row), 1)
    },
    handleSelectedGoods(obj, row) {
      row.spuId = obj.id
      row.spuName = obj.spuName
      row.brandId = obj.brandId
      row.brandName = obj.brandName
      row.categoryId = obj.categoryId
      row.categoryName = obj.categoryName
      row.sn = obj.sn
      row.price = obj.price
      row.qty = 1
      row.image = obj.image
    },
    handleTotal() {
      let totalQty = 0
      let totalMoney = 0
      if (this.salesOrder.items.length > 0) {
        this.salesOrder.items.forEach(item => {
          totalQty += Number(item.qty)
          totalMoney += item.price * item.qty
        })
      }
      this.salesOrder.totalQty = totalQty
      this.salesOrder.totalMoney = totalMoney
    },
    handleSave() {
      SalesOrderApi.save(this.salesOrder).then(response => {
        this.$message.success('保存成功')
        this.$router.go(-1)
      })
    },
    handleSubmit() {
      SalesOrderApi.submit(this.salesOrder).then(response => {
        this.$message.success('提交成功')
        this.$router.go(-1)
      })
    },
    handleDownloadQuote() {
      SalesOrderApi.downloadQuote(this.salesOrder.id).then(response => {
        if (response.data) {
          this.$common.download(response.data)
        } else {
          this.$message.warning('请先保存/提交订单')
        }
      })
    },
    handleConfirmQuote() {
      SalesOrderApi.confirmQuote(this.salesOrder.id).then(response => {
        this.$message.success('确认提案成功')
        this.init()
      })
    },
    handleSignContract() {
      const params = {
        id: this.salesOrder.id,
        contractNo: this.salesOrder.contractNo
      }
      SalesOrderApi.signContract(params).then(response => {
        this.$message.success('合同签订成功')
        this.signContractDialogVisible = false
        this.init()
      })
    },
    handleConfirmPay() {
      const params = {
        id: this.salesOrder.id,
        payType: this.salesOrder.payType,
        transactionId: this.salesOrder.transactionId
      }
      SalesOrderApi.confirmPay(params).then(response => {
        this.$message.success('确认支付成功')
        this.confirmPayDialogVisible = false
        this.init()
      })
    },
    handleDeliveryPlan() {
      const params = {
        id: this.salesOrder.id
      }
      SalesOrderApi.deliveryPlan(params).then(response => {
        this.$message.success('发货计划成功')
        this.deliveryPlanDialogVisible = false
        this.init()
      })
    },
    handleDelivery() {
      const params = {
        id: this.salesOrder.id,
        expressCompanyName: this.salesOrder.expressCompanyName,
        expressNo: this.salesOrder.expressNo
      }
      SalesOrderApi.delivery(params).then(response => {
        this.$message.success('发货成功')
        this.deliveryDialogVisible = false
        this.init()
      })
    },
    stepStatusFormat(orderStatus) {
      if (orderStatus === 'created') {
        return 2
      }
      if (orderStatus === 'submitted') {
        return 3
      }
      if (orderStatus === 'unconfirmed') {
        return 4
      }
      if (orderStatus === 'confirmed') {
        return 5
      }
      if (orderStatus === 'contract_signed') {
        return 6
      }
      if (orderStatus === 'delivery_plan') {
        return 7
      }
      if (orderStatus === 'delivered') {
        return 8
      }
      if (orderStatus === 'completed') {
        return 9
      }
      return 1
    },
    orderStatusFormat(status) {
      return this.$common.getDictValueName(this.options.salesOrderStatusOptions, status)
    },
    orderTypeFormat(type) {
      return this.$common.getDictValueName(this.options.orderTypeOptions, type)
    },
    payTypeFormat(type) {
      return this.$common.getDictValueName(this.options.payTypeOptions, type)
    },
    expressInfoFormat(salesOrder) {
      const expressCompanyName = salesOrder.expressCompanyName ? salesOrder.expressCompanyName : ''
      const expressNo = salesOrder.expressNo ? salesOrder.expressNo : ''
      return expressCompanyName + ' ' + expressNo
    }
  }
}
</script>
<style scoped>
  .detail-container {
    width: 80%;
    padding: 20px 20px 20px 20px;
    margin: 20px auto;
  }

  .operate-container {
    background: #F2F6FC;
    height: 80px;
    margin: -20px -20px 0;
    line-height: 80px;
  }

  .operate-button-container {
    float: right;
    margin-right: 20px
  }

  .table-layout {
    margin-top: 20px;
    border-left: 1px solid #DCDFE6;
    border-top: 1px solid #DCDFE6;
  }

  .table-cell {
    height: 60px;
    line-height: 40px;
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    font-size: 14px;
    color: #606266;
    text-align: center;
    overflow: hidden;
  }

  .table-cell-title {
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
    padding: 10px;
    background: #F2F6FC;
    text-align: center;
    font-size: 14px;
    color: #303133;
  }
</style>
